<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use app\admin\controller\Cloudaccountwithdraw;
use OSS\OssClient;
use think\Db;
use think\Request;
use app\common\model\User;
use app\common\model\UserLevel;
use app\common\validate\UserValidate;

require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');
class FawithdrawnewController extends Controller
{

    /**
     * 提现审核列表
     * User:@hang
     */
    public function index(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['b.member_id','=',$param['member_id']];
        }
        if (isset($param['me_uid']) && !empty($param['me_uid'])) {
            $whehe[] = ['b.me_uid','=',$param['me_uid']];
        }
        if (isset($param['me_phone']) && !empty($param['me_phone'])) {
            $whehe[] = ['b.me_phone|b.me_nick_name','like',"%{$param['me_phone']}%"];
        }
        if (isset($param['me_sex']) && !empty($param['me_sex'])) {
            $whehe[] = ['b.me_sex','=',$param['me_sex']];
        }
        if (isset($param['order_number']) && !empty($param['order_number'])) {
            $whehe[] = ['a.order_number','like',"%{$param['order_number']}%"];
        }
        if (isset($param['status']) && $param['status'] != '') {
            $whehe[] = ['a.status','=',$param['status']];
        }
        if (isset($param['sk_type']) && !empty($param['sk_type'])) {
            $whehe[] = ['a.sk_type','=',$param['sk_type']];
        }
        if (isset($param['is_pending']) && $param['is_pending'] != '') {
            $whehe[] = ['a.is_pending','=',$param['is_pending']];
        }
        if (isset($param['is_pass_withdrawal']) && $param['is_pass_withdrawal'] != '') {
            $whehe[] = ['b.is_pass_withdrawal','=',$param['is_pass_withdrawal']];
        }
        $whehetime = '';$start_time = 0;$end_time = 0;
        if (isset($param['add_time']) && !empty($param['add_time'])) {
            $time_arr = explode(' - ', $param['add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1]);
            $whehetime = "a.add_time >= $start_time AND a.add_time <= $end_time";
        }
        if (isset($param['f_member_id']) && !empty($param['f_member_id'])) {
            $whehe[] = ['a.f_id','=',$param['f_member_id']];
        }


        //银行卡 提现列表导出表格
        if (isset($param['export_data']) && $param['export_data'] == 1) {
            $whehe[] = ['a.status','=','0'];
            $whehe[] = ['a.sk_type','=','3'];
            $whehe[] = ['b.me_status','=','1'];
            $whehe[] = ['a.is_pending','=','0'];
            $data = Db::table('fa_zwithdrawal_order')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->where($whehe)
                ->where($whehetime)
                ->field('a.*,b.me_realname,b.me_realidcard')
                ->order('a.add_time desc')
                ->select();
            if(!empty($data)){
                foreach ($data as $k=>$v){
                    $data[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
                }
            }
            //提现总金额
            $allMoney = Db::table('fa_zwithdrawal_order')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->where($whehe)
                ->where($whehetime)->sum('actual_withdrawal');
            $allMoney = delete0(bcadd($allMoney,0,2));
            //导出表格
            $start_time_date = empty($start_time)?'全部时间':date('m月d日H时i分',$start_time);
            $end_time_date = empty($end_time)?'全部时间':date('m月d日H时i分',$end_time);
            $filename = '银行卡('.$start_time_date.'~'.$end_time_date.')';
            $download_url = $this->setexcel_yhk($filename,$data,$allMoney);//服务器文件地址
            //文件存储到阿里云OSS
            $config['KeyId'] = 'LTAI5t7z9G5JTNzezZd6bRAj';
            $config['KeySecret'] = '1VDtHWYwk7KWZRikFra1I28AlPMGd5';
            $config['Bucket'] = 'uploads-ydxc';
            $config['Endpoint'] = 'oss-accelerate.aliyuncs.com';
            //实例化对象 将配置传入
            $ossClient = new OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']);
            //这里是有sha1加密 生成文件名 之后连接上后缀
            $fileName = '1excel/'.$filename.'.xlsx';
            //执行阿里云上传
            $result = $ossClient->uploadFile($config['Bucket'], $fileName, $download_url);
            if(!isset($result['info']['url'])){
                return admin_error('OSS表格地址获取失败',URL_CLOSE_REFRESH);
            }
            if(empty($result['info']['url'])){
                return admin_error('OSS表格地址为空',URL_CLOSE_REFRESH);
            }
            $oss_download_url = $result['info']['url'];
            // 发送HTTP头信息，告诉浏览器这是一个要下载的文件
            header('Content-Type: application/octet-stream');
            header("Content-Disposition: attachment; filename=".$filename.".xlsx");
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            // 读取文件内容并输出到浏览器
            readfile($oss_download_url);
            exit;
        }


        //支付宝 提现列表导出表格
        if (isset($param['export_data']) && $param['export_data'] == 2) {
            $whehe[] = ['a.status','=','0'];
            $whehe[] = ['a.sk_type','=','2'];
            $whehe[] = ['b.me_status','=','1'];
            $whehe[] = ['a.is_pending','=','0'];
            $data = Db::table('fa_zwithdrawal_order')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->where($whehe)
                ->where($whehetime)
                ->field('a.*,b.me_phone,b.me_realname,b.me_realidcard')
                ->order('a.add_time desc')
                ->select();
            if(!empty($data)){
                foreach ($data as $k=>$v){
                    $data[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
                }
            }
            //提现总金额
            $allMoney = Db::table('fa_zwithdrawal_order')
                ->alias('a')
                ->join("fa_member b",'a.member_id = b.member_id','LEFT')
                ->where($whehe)
                ->where($whehetime)->sum('actual_withdrawal');
            $allMoney = delete0(bcadd($allMoney,0,2));
            //导出表格
            $start_time_date = empty($start_time)?'全部时间':date('m月d日H时i分',$start_time);
            $end_time_date = empty($end_time)?'全部时间':date('m月d日H时i分',$end_time);
            $filename = '支付宝('.$start_time_date.'~'.$end_time_date.')';
            $download_url = $this->setexcel_zfb($filename,$data,$allMoney);//服务器文件地址
            //文件存储到阿里云OSS
            $config['KeyId'] = 'LTAI5t7z9G5JTNzezZd6bRAj';
            $config['KeySecret'] = '1VDtHWYwk7KWZRikFra1I28AlPMGd5';
            $config['Bucket'] = 'uploads-ydxc';
            $config['Endpoint'] = 'oss-accelerate.aliyuncs.com';
            //实例化对象 将配置传入
            $ossClient = new OssClient($config['KeyId'], $config['KeySecret'], $config['Endpoint']);
            //这里是有sha1加密 生成文件名 之后连接上后缀
            $fileName = '1excel/'.$filename.'.xlsx';
            //执行阿里云上传
            $result = $ossClient->uploadFile($config['Bucket'], $fileName, $download_url);
            if(!isset($result['info']['url'])){
                return admin_error('OSS表格地址获取失败',URL_CLOSE_REFRESH);
            }
            if(empty($result['info']['url'])){
                return admin_error('OSS表格地址为空',URL_CLOSE_REFRESH);
            }
            $oss_download_url = $result['info']['url'];
            // 发送HTTP头信息，告诉浏览器这是一个要下载的文件
            header('Content-Type: application/octet-stream');
            header("Content-Disposition: attachment; filename=".$filename.".xlsx");
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            // 读取文件内容并输出到浏览器
            readfile($oss_download_url);
            exit;
        }



        $data = Db::table('fa_zwithdrawal_order')
            ->alias('a')
            ->join("fa_member b",'a.member_id = b.member_id','LEFT')
            ->join("fa_member c",'a.f_id = c.member_id','LEFT')
            ->join("fa_member_fund d",'a.member_id = d.member_id','LEFT')
            ->where($whehe)
            ->where($whehetime)
            ->field('a.*,b.me_uid,b.me_phone,b.me_nick_name,b.me_sex,b.me_realname,b.me_realidcard,b.me_status,c.member_id as f_member_id,c.me_uid as f_me_uid,c.me_nick_name as f_me_nick_name,d.stamp_money,d.no_stamp_money,b.is_pass_withdrawal,b.bz_name,b.me_zhuxiao')
            ->order('a.add_time desc')
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);

        $start_time = strtotime(date('Y-m-d',time()));
        $end_time = $start_time + 86399;
        $last_start_time = $start_time - 86400;
        $last_end_time = $end_time - 86400;

        $adminid = $this->uid;
        $data->each(function ($v, $k)use($adminid,$last_start_time,$last_end_time) {

            switch($v['is_pass_withdrawal']){
                case '0': $v['is_pass_withdrawal_word'] = '未开启';break;
                case '1': $v['is_pass_withdrawal_word'] = '已开启';break;
            }

            //只有超管能看全部手机号
            if($adminid != 1){
                $v['me_phone'] = hide_phone_number($v['me_phone']);
            }
            $v['tr_color'] = '0';//无颜色
            if($v['add_time'] >= $last_start_time && $v['add_time'] <= $last_end_time){
                $v['tr_color'] = '1';
            }
            if($v['me_sex'] == 1){
                $v['tr_color'] = '2';
            }
            if(empty($v['f_member_id'])){
                $v['tr_color'] = '3';
            }

            switch($v['is_pending']){
                case '0': $v['is_pending_word'] = '未设置';break;
                case '1': $v['is_pending_word'] = '已设置';break;
            }
            switch($v['status']){
                case '0': $v['status_word'] = '待审核';break;
                case '1':
                    $v['status_word'] = '同意提现';
                    if($v['operation_user_id'] == -99){
                        $v['status_word'] .= '(免审核)';
                    }
                break;
                case '2': $v['status_word'] = '拒绝提现';break;
            }
            switch($v['me_sex']){
                case '0': $v['me_sex_word'] = '未设置';break;
                case '1': $v['me_sex_word'] = '男';break;
                case '2': $v['me_sex_word'] = '女';break;
            }

            $v['me_status_word'] = '正常';
            if($v['me_zhuxiao'] == 1){
                $v['me_status_word'] = '已注销';
                if(!empty(strpos($v['me_realname'], 'zx'))){
                    $v['me_realname'] = explode('zx',$v['me_realname'])[0];
                }
            }else{
                if($v['me_status'] == 2){
                   $v['me_status_word'] = '已封禁';
                }
            }

            if($v['sk_type'] == 1){
                $v['sk_type_word'] = '微信';
                $v['sk_type_info'] = '用户微信';
            }
            if($v['sk_type'] == 2){
                $v['sk_type_word'] = '支付宝';
                $v['sk_type_info'] = $v['alipay_name'].' '.$v['alipay_number'];
            }
            if($v['sk_type'] == 3){
                $v['sk_type_word'] = '银行卡';
                $v['sk_type_info'] = $v['bank_phone'].' '.$v['bank_name'].' '.$v['bank_number'].' '.$v['bank_kh'];
            }

            if(!empty($v['content'])){
                $v['content_sl'] = cutStr($v['content'],5);
            }else{
                $v['content_sl'] = '未审核';
            }
            $v['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
            $v['operation_time'] = !empty($v['operation_time'])?date('Y-m-d H:i:s',$v['operation_time']):'未审核';
            $v['after_money_word'] = $v['after_money'] == -1?'-':$v['after_money'];

            $djMemberId = getDjParent($v['member_id']);
            $v['dj_member_id'] = $djMemberId['dj_member_id'];
            if(empty($djMemberId['bz_name'])){
                $v['dj_member_word'] = empty($djMemberId['dj_member_id'])?'自身':$djMemberId['dj_member_id'];
            }else{
                $v['dj_member_word'] = empty($djMemberId['dj_member_id'])?'自身':$djMemberId['dj_member_id'].'【'.$djMemberId['bz_name'].'】';
            }

            return $v;
        });

        //提现待审核总金额
        $dsh_money = Db::table('fa_zwithdrawal_order')
            ->alias('a')
            ->join("fa_member b",'a.member_id = b.member_id','LEFT')
            ->where("`status` = 0")
            ->where($whehe)
            ->where($whehetime)
            ->sum('a.actual_withdrawal');
        $yzhyc_money = delete0(bcmul($dsh_money,1.065,4));
        //提现通过总金额
        $tg_money = Db::table('fa_zwithdrawal_order')
            ->alias('a')
            ->join("fa_member b",'a.member_id = b.member_id','LEFT')
            ->where("`status` = 1")
            ->where($whehe)
            ->where($whehetime)
            ->sum('a.actual_withdrawal');
        //提现拒绝总金额
        $jj_money = Db::table('fa_zwithdrawal_order')
            ->alias('a')
            ->join("fa_member b",'a.member_id = b.member_id','LEFT')
            ->where("`status` = 2")
            ->where($whehe)
            ->where($whehetime)
            ->sum('a.actual_withdrawal');

        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
            'dsh_money' => $dsh_money,
            'tg_money' => $tg_money,
            'jj_money' => $jj_money,
            'yzhyc_money' => $yzhyc_money,
        ]);
        return $this->fetch();
    }



    /**
     * 通过提现 页面
     * User:@hang
     */
    public function passwithdraw($id)
    {
        //查询提现详情
        $IndexTableModel = New IndexTableModel();
        $info = $IndexTableModel->getFind('fa_zwithdrawal_order',"`id` = '{$id}'",'*');
        if(empty($info)){
            return admin_error('提现信息未查询到',URL_CLOSE_REFRESH);
        }
        $is_show = '1';
        if($info['status'] != 0){
            $is_show = '这笔提现已经处理过，请关闭弹框，刷新页面再看！';
        }
        switch($info['sk_type']){
            case '1': $info['sk_type_word'] = '微信';break;
            case '2': $info['sk_type_word'] = '支付宝';break;
            case '3': $info['sk_type_word'] = '银行卡';break;
        }
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$info['member_id']}'",'member_id,me_uid,me_phone,me_nick_name,me_sex,me_realname,me_realidcard');
        switch($memberInfo['me_sex']){
            case '0': $memberInfo['me_sex_word'] = '未设置';break;
            case '1': $memberInfo['me_sex_word'] = '男';break;
            case '2': $memberInfo['me_sex_word'] = '女';break;
        }
        $info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);

//        $fee_list = ['7'=>'7%','6.5'=>'6.5%'];
        $fee_list = [];

        $this->assign([
            'data' => $id,
            'info' => $info,
            'memberinfo' => $memberInfo,
            'ql_fee' => $info['fee_bl'],
            'ql_fee_word' => $info['fee_bl'].'（系统默认）',
            'fee_list' => $fee_list,
            'is_show' => $is_show,
        ]);
        return $this->fetch();
    }

    /**
     * 确认 通过提现
     * User:@hang
     */
    public function actionpasswithdraw()
    {
        $fee_zx_bl = input('fee_zx_bl');//执行的提现手续费比例
        $id = input('id');
        $content = replaceSpecialChar(input('content'));
        if(empty($content)){
            $content = '已通过用户的提现申请';
        }
        $IndexTableModel = New IndexTableModel();
        $tinfo = $IndexTableModel->getFind('fa_zwithdrawal_order',"`id` = '{$id}'",'*');
        if(empty($tinfo)){
            return admin_error('提现信息未查询到',URL_CLOSE_REFRESH);
        }
        if($tinfo['status'] != 0){
            return admin_error('提现申请已经处理过，无需再次处理',URL_CLOSE_REFRESH);
        }
        if($tinfo['is_pending'] == 1){
            return admin_error('已经设置待定，不可审核此提现',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionpasswithdraw'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        Db::startTrans();

        //计算真实到账金额
        if($tinfo['fee_bl'] == $fee_zx_bl){
            //无更改
            $fee_bl = $fee_zx_bl;//手续费比例
            $fee_withdrawal = $tinfo['fee_withdrawal'];//手续费油票数
            $payMoney = delete0(bcadd($tinfo['actual_withdrawal'],0,2));//到账金额
        }else{
            //有更改
            $fee_bl = $fee_zx_bl;//手续费比例
            $withdrawfee = bcdiv($fee_bl,100,4);
            $fee_withdrawal = delete0(bcmul($withdrawfee,$tinfo['total_withdrawal'],2));//手续费油票数
            //计算真实到账金额
            $Common = New Common();
            $stampmoney = $Common->getConfigValue('stampmoney');//1油票价值人民币
            $actual_withdrawal = delete0(bcmul(bcsub($tinfo['total_withdrawal'],$fee_withdrawal,2),$stampmoney,2));
            $payMoney = delete0(bcadd($actual_withdrawal,0,2));//到账金额
        }

        //修改提现订单状态
        $res = $IndexTableModel->editInfo('fa_zwithdrawal_order',"`id` = '{$id}'",array('status'=>1,'operation_user_id'=>$this->uid,'operation_time'=>$ctime,'content'=>$content,'fee_bl'=>$fee_bl,'fee_withdrawal'=>$fee_withdrawal,'actual_withdrawal'=>$payMoney,'is_pending'=>0));
        if(empty($res)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改提现订单状态失败',URL_CLOSE_REFRESH);
        }
        //增加财务日志
        $member_money = $IndexTableModel->getFind('fa_member_fund',"`member_id` = '{$tinfo['member_id']}'",'member_id,stamp_money');
        $member_money_stamp_money = !empty($member_money)?$member_money['stamp_money']:'0.00';
        $financeRes = $IndexTableModel->addInfo('fa_finance',array('member_id'=>$tinfo['member_id'],'d_member_id'=>0,'g_table'=>'fa_zwithdrawal_order','g_id'=>$id,'type'=>15,'money_type'=>2,'status'=>2,'money'=>$tinfo['total_withdrawal'],'member_money'=>$member_money_stamp_money,'content'=>'您于【'.date('Y-m-d H:i:s',$tinfo['add_time']).'】提现已经通过'.'（流水号：'.$tinfo['order_number'].'）','add_time'=>$ctime,'chat_type'=>0));
        if(empty($financeRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('增加通过提现财务日志',URL_CLOSE_REFRESH);
        }
        //添加服务通知
        switch($tinfo['sk_type']){
            case '1': $sk_type_word = '微信';break;
            case '2': $sk_type_word = '支付宝';break;
            case '3': $sk_type_word = '银行卡';break;
        }
        $newsRes = $IndexTableModel->addInfo('fa_news_service',array('type'=>3,'member_id'=>0,'j_member_id'=>$tinfo['member_id'],'g_table'=>'fa_zwithdrawal_order','g_id'=>$id,'content'=>'恭喜，您于【'.date('Y-m-d H:i:s',$tinfo['add_time']).' 的'.$sk_type_word.'提现申请已经通过，提现油票数'.$tinfo['total_withdrawal'].'，实际到账金额'.$payMoney.'元】，通过时间：'.date('Y-m-d H:i:s',$ctime).'，通过理由：【'.$content.'】'.'，您可以到对应账户查看到账情况。'.'（流水号：'.$tinfo['order_number'].'）','is_read'=>0,'add_time'=>$ctime));
        if(empty($newsRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('添加服务通知失败',URL_CLOSE_REFRESH);
        }
        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('通过提现成功',URL_CLOSE_REFRESH);
    }


    /**
     * 拒绝提现 页面
     * User:@hang
     */
    public function refusewithdraw($id)
    {
        //查询提现详情
        $IndexTableModel = New IndexTableModel();
        $info = $IndexTableModel->getFind('fa_zwithdrawal_order',"`id` = '{$id}'",'*');
        $is_show = '1';
        if($info['status'] != 0){
            $is_show = '这笔提现已经处理过，请关闭弹框，刷新页面再看！';
        }
        switch($info['sk_type']){
            case '1': $info['sk_type_word'] = '微信';break;
            case '2': $info['sk_type_word'] = '支付宝';break;
            case '3': $info['sk_type_word'] = '银行卡';break;
        }
        $info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$info['member_id']}'",'member_id,me_uid,me_phone,me_nick_name,me_sex,me_realname,me_realidcard');
        switch($memberInfo['me_sex']){
            case '0': $memberInfo['me_sex_word'] = '未设置';break;
            case '1': $memberInfo['me_sex_word'] = '男';break;
            case '2': $memberInfo['me_sex_word'] = '女';break;
        }
        $this->assign([
            'data' => $id,
            'info' => $info,
            'memberinfo' => $memberInfo,
            'is_show' => $is_show
        ]);
        return $this->fetch();
    }



    /**
     * 确认 拒绝提现
     * User:@hang
     */
    public function actionrefusewithdraw()
    {
        $id = input('id');
        $content = replaceSpecialChar(input('content'));
        if(empty($content)){
            $content = '您的提现已拒绝，请联系客服';
        }
        $IndexTableModel = New IndexTableModel();
        $tinfo = $IndexTableModel->getFind('fa_zwithdrawal_order',"`id` = '{$id}'",'*');
        if(empty($tinfo)){
            return admin_error('提现信息未查询到',URL_CLOSE_REFRESH);
        }
        if($tinfo['status'] != 0){
            return admin_error('提现申请已经处理过，无需再次处理',URL_CLOSE_REFRESH);
        }
        if($tinfo['is_pending'] == 1){
            return admin_error('已经设置待定，不可审核此提现',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionrefusewithdraw'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $ctime = time();
        Db::startTrans();
        $tmemberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$tinfo['member_id']}'",'member_id,me_uid,me_phone,me_nick_name,me_sex,me_realname,me_realidcard,me_is_real,me_yzh');
        if(empty($tmemberInfo)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('您的用户信息未查询到',URL_CLOSE_REFRESH);
        }
        //修改提现订单状态
        $res = $IndexTableModel->editInfo('fa_zwithdrawal_order',"`id` = '{$id}'",array('status'=>2,'operation_user_id'=>$this->uid,'operation_time'=>$ctime,'content'=>$content,'is_pending'=>0));
        if(empty($res)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改提现订单状态失败',URL_CLOSE_REFRESH);
        }
        $total_withdrawal = $tinfo['total_withdrawal'];//返还用户油票数
        $Common = New Common();
        //增加用户油票数
        $yp_res = $Common->incStampMoney($tinfo['member_id'],1,$total_withdrawal);
        if($yp_res != 200){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('加用户可提现油票数失败',URL_CLOSE_REFRESH);
        }
        //增加用户财务日志
        $finRes = $Common->setFinance($tinfo['member_id'],0,'fa_zwithdrawal_order',$id,14,2,1,$total_withdrawal,'您于【'.date('Y-m-d H:i:s',$tinfo['add_time']).'】提现已被拒绝'.'（流水号：'.$tinfo['order_number'].'）',0);
        if($finRes['code'] != 200){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('增加用户财务日志失败',URL_CLOSE_REFRESH);
        }
        //添加服务通知
        switch($tinfo['sk_type']){
            case '1': $sk_type_word = '微信';break;
            case '2': $sk_type_word = '支付宝';break;
            case '3': $sk_type_word = '银行卡';break;
        }
        $newsRes = $IndexTableModel->addInfo('fa_news_service',array('type'=>4,'member_id'=>0,'j_member_id'=>$tinfo['member_id'],'g_table'=>'fa_zwithdrawal_order','g_id'=>$id,'content'=>'抱歉，您于【'.date('Y-m-d H:i:s',$tinfo['add_time']).' 的'.$sk_type_word.'提现申请被拒绝，提现油票数'.$tinfo['total_withdrawal'].'】，拒绝时间：'.date('Y-m-d H:i:s',$ctime).'，拒绝理由【'.$content.'】，油票已返还到原账户，您可以到钱包中查看。'.'（流水号：'.$tinfo['order_number'].'）','is_read'=>0,'add_time'=>$ctime));
        if(empty($newsRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('添加服务通知失败',URL_CLOSE_REFRESH);
        }
        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('拒绝提现成功',URL_CLOSE_REFRESH);
    }



    //设置/取消 待定标签
    public function setpending($id){
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:setpending'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试！',URL_CLOSE_REFRESH);
        }
        $index = input('index');
        $IndexTableModel = New IndexTableModel();
        $res = $IndexTableModel->editInfo('fa_zwithdrawal_order',"`id` = '{$id}'",array('is_pending'=>$index));
        if(empty($res)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('操作失败',URL_CLOSE_REFRESH);
        }
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('操作成功', URL_RELOAD);
    }


    /**
     * 批量通过提现
     * User:@hang
     */
    public function actionpltg()
    {
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionpltg';	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $id_arr = input('id/a');
        if(empty($id_arr)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('请选择要通过的提现订单！',URL_CLOSE_REFRESH);
        }
        $content = replaceSpecialChar(input('sh_content'));
        if(empty($content)){
            $content = '已通过用户的提现申请';
        }
        $IndexTableModel = New IndexTableModel();
        foreach ($id_arr as $k=>$v){
            $tinfo = $IndexTableModel->getFind('fa_zwithdrawal_order',"`id` = '{$v}'",'id,status,is_pending');
            if(empty($tinfo)){
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('部分提现信息未查询到',URL_CLOSE_REFRESH);
            }
            if($tinfo['status'] != 0){
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('选中的订单中，存在【已经处理】的订单，请刷新页面后从新选择',URL_CLOSE_REFRESH);
            }
            if($tinfo['is_pending'] == 1){
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('选中的订单中，存在已经设置【待定】的订单，请刷新页面后从新选择',URL_CLOSE_REFRESH);
            }
        }

        $ctime = time();
        Db::startTrans();
        //批量处理通过
        foreach ($id_arr as $k=>$v){
            //修改提现订单状态
            $res = $IndexTableModel->editInfo('fa_zwithdrawal_order',"`id` = '{$v}'",array('status'=>1,'operation_user_id'=>$this->uid,'operation_time'=>$ctime,'content'=>$content,'is_pending'=>0));
            if(empty($res)){
                Db::rollBack();
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('修改提现订单ID'.$v.'状态失败',URL_CLOSE_REFRESH);
            }
            $tinfo = $IndexTableModel->getFind('fa_zwithdrawal_order',"`id` = '{$v}'",'*');//提现信息
            //增加财务日志
            $member_money = $IndexTableModel->getFind('fa_member_fund',"`member_id` = '{$tinfo['member_id']}'",'member_id,stamp_money');
            $member_money_stamp_money = !empty($member_money)?$member_money['stamp_money']:'0.00';
            $financeRes = $IndexTableModel->addInfo('fa_finance',array('member_id'=>$tinfo['member_id'],'d_member_id'=>0,'g_table'=>'fa_zwithdrawal_order','g_id'=>$v,'type'=>15,'money_type'=>2,'status'=>2,'money'=>$tinfo['total_withdrawal'],'member_money'=>$member_money_stamp_money,'content'=>'您于【'.date('Y-m-d H:i:s',$tinfo['add_time']).'】提现已经通过'.'（流水号：'.$tinfo['order_number'].'）','add_time'=>$ctime,'chat_type'=>0));
            if(empty($financeRes)){
                Db::rollBack();
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('增加通过提现ID'.$v.'财务日志失败',URL_CLOSE_REFRESH);
            }
            //添加服务通知
            switch($tinfo['sk_type']){
                case '1': $sk_type_word = '微信';break;
                case '2': $sk_type_word = '支付宝';break;
                case '3': $sk_type_word = '银行卡';break;
            }
            $newsRes = $IndexTableModel->addInfo('fa_news_service',array('type'=>3,'member_id'=>0,'j_member_id'=>$tinfo['member_id'],'g_table'=>'fa_zwithdrawal_order','g_id'=>$v,'content'=>'恭喜，您于【'.date('Y-m-d H:i:s',$tinfo['add_time']).' 的'.$sk_type_word.'提现申请已经通过，提现油票数'.$tinfo['total_withdrawal'].'，实际到账金额'.$tinfo['actual_withdrawal'].'元】，通过时间：'.date('Y-m-d H:i:s',$ctime).'，通过理由：【'.$content.'】'.'，您可以到对应账户查看到账情况。'.'（流水号：'.$tinfo['order_number'].'）','is_read'=>0,'add_time'=>$ctime));
            if(empty($newsRes)){
                Db::rollBack();
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('添加服务通知失败',URL_CLOSE_REFRESH);
            }
        }

        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('批量通过提现成功',URL_RELOAD);
    }






    /**
     * 为此用户设置备注姓名 页面
     * User:@hang
     */
    public function setbzname($id)
    {
        //查询提现详情
        $IndexTableModel = New IndexTableModel();
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$id}'",'member_id,me_uid,me_phone,me_nick_name,me_sex,me_realname,me_realidcard,bz_name');
        $this->assign([
            'data' => $id,
            'memberinfo' => $memberInfo,
        ]);
        return $this->fetch();
    }


    /**
     * 确认 修改用户备注姓名
     * User:@hang
     */
    public function actionsetbzname()
    {
        $id = input('id');
        $bz_name = input('bz_name');
        $IndexTableModel = New IndexTableModel();
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionsetbzname'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试',URL_CLOSE_REFRESH);
        }
        $IndexTableModel->editInfo('fa_member',"`member_id` = {$id}",['bz_name'=>$bz_name]);
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('设置成功',URL_CLOSE_REFRESH);
    }













    /**
     * 银行卡 生成excel表格
     * User:@hang
     */
    public function setexcel_yhk($fileName,$data,$allMoney){
        //引用phpexcel
        require_once(__DIR__ . '/../../../vendor/PHPExcel/PHPExcel.php');
        require_once(__DIR__ . '/../../../vendor/PHPExcel/PHPExcel/IOFactory.php');
        // import('PHPExcel.PHPExcel',EXTEND_PATH,'.php');
        // import('PHPExcel.PHPExcel.IOFactory',EXTEND_PATH,'.php');
        $excel = new \PHPExcel();
        $name = $fileName;
        //针对中文名转码
        iconv('UTF-8', 'gb2312', $name);
        //表头,名称可自定义
        $excel->setActiveSheetIndex(0);
        //设置表名
        $excel->getActiveSheet()->setTitle($name);
        //所有行默认高度
//        $excel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(18);
        // 第一行的默认高度
        $excel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);
        //列坐标
        $letter = ['A','B','C','D','E','F','G','H','I','J','K'];
        //生成表头
        $header = ['姓名','手机号','身份证号','申请金额（元）','银行卡号','银行名称','提现时间','提现ID','序列号','提现总笔数','提现总金额'];
        for($i=0;$i<count($header);$i++){
            // 设置表头值
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", $header[$i]);
            // 设置表头字体样式
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setName('等线');
            // 设置表头字体大小
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setSize(14);
            // 设置表头字体是否加粗（改为不加粗，即 false ）
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setBold(true);
            // 设置表头文字水平居中
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            // 设置文字上下居中
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
//            // 设置单元格背景色（白色，#FFFFFF  ）
//            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFill()->getStartColor()->setARGB('FFFFFFFF');
//            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
//            // 设置字体颜色（黑色，#000000  ）
//            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->getColor()->setARGB('00000000');
        }
        $excel->getActiveSheet()->getColumnDimension("A")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("B")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("C")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("D")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("E")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("F")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("G")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("H")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("I")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("J")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("K")->setWidth(20);
        if(!empty($data)){
            $allNum = count($data);
            //写入数据
            foreach($data as $k=>$v){
                //从第二行开始写入数据（第一行为表头）
                $excel->getActiveSheet()->setCellValueExplicit('A'.($k+2),$v['bank_name'])->getStyle('A'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('B'.($k+2),$v['bank_phone'])->getStyle('B'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('C'.($k+2),$v['me_realidcard'])->getStyle('C'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('D'.($k+2),$v['actual_withdrawal'])->getStyle('D'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('E'.($k+2),$v['bank_number'])->getStyle('E'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('F'.($k+2),$v['bank_kh'])->getStyle('F'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('G'.($k+2),$v['add_time'])->getStyle('G'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('H'.($k+2),$v['id'])->getStyle('H'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('I'.($k+2),($k+1))->getStyle('I'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

                if($k == 0){
                    $excel->getActiveSheet()->setCellValueExplicit('J'.($k+2),$allNum.' 笔')->getStyle('J'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $excel->getActiveSheet()->setCellValueExplicit('K'.($k+2),$allMoney.' 元')->getStyle('K'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                }
            }
        }

        //清理缓冲区，避免中文乱码
        ob_end_clean();
        //导出数据
        $obj=new \PHPExcel_Writer_Excel5($excel);//实例化 将对象放入表格中
        $download_url = './uploads/1excel/'.$name.'.xlsx'; //生成表格地址
        $obj->save($download_url);
        return $download_url;
    }


    /**
     * 支付宝 生成excel表格
     * User:@hang
     */
    public function setexcel_zfb($fileName,$data,$allMoney){
        //引用phpexcel
        require_once(__DIR__ . '/../../../vendor/PHPExcel/PHPExcel.php');
        require_once(__DIR__ . '/../../../vendor/PHPExcel/PHPExcel/IOFactory.php');
        // import('PHPExcel.PHPExcel',EXTEND_PATH,'.php');
        // import('PHPExcel.PHPExcel.IOFactory',EXTEND_PATH,'.php');
        $excel = new \PHPExcel();
        $name = $fileName;
        //针对中文名转码
        iconv('UTF-8', 'gb2312', $name);
        //表头,名称可自定义
        $excel->setActiveSheetIndex(0);
        //设置表名
        $excel->getActiveSheet()->setTitle($name);
        //所有行默认高度
//        $excel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(18);
        // 第一行的默认高度
        $excel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);
        //列坐标
        $letter = ['A','B','C','D','E','F','G','H','I','J'];
        //生成表头
        $header = ['姓名','手机号','身份证号','申请金额（元）','支付宝账号','提现时间','提现ID','序列号','提现总笔数','提现总金额'];
        for($i=0;$i<count($header);$i++){
            // 设置表头值
            $excel->getActiveSheet()->setCellValue("$letter[$i]1", $header[$i]);
            // 设置表头字体样式
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setName('等线');
            // 设置表头字体大小
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setSize(14);
            // 设置表头字体是否加粗（改为不加粗，即 false ）
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setBold(true);
            // 设置表头文字水平居中
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            // 设置文字上下居中
            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
//            // 设置单元格背景色（白色，#FFFFFF  ）
//            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFill()->getStartColor()->setARGB('FFFFFFFF');
//            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
//            // 设置字体颜色（黑色，#000000  ）
//            $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->getColor()->setARGB('00000000');
        }
        $excel->getActiveSheet()->getColumnDimension("A")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("B")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("C")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("D")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("E")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("F")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("G")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("H")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("I")->setWidth(20);
        $excel->getActiveSheet()->getColumnDimension("J")->setWidth(20);
        if(!empty($data)){
            $allNum = count($data);
            //写入数据
            foreach($data as $k=>$v){
                //从第二行开始写入数据（第一行为表头）
                $excel->getActiveSheet()->setCellValueExplicit('A'.($k+2),$v['alipay_name'])->getStyle('A'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('B'.($k+2),$v['me_phone'])->getStyle('B'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('C'.($k+2),$v['me_realidcard'])->getStyle('C'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('D'.($k+2),$v['actual_withdrawal'])->getStyle('D'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('E'.($k+2),$v['alipay_number'])->getStyle('E'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('F'.($k+2),$v['add_time'])->getStyle('F'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('G'.($k+2),$v['id'])->getStyle('G'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $excel->getActiveSheet()->setCellValueExplicit('H'.($k+2),($k+1))->getStyle('H'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

                if($k == 0){
                    $excel->getActiveSheet()->setCellValueExplicit('I'.($k+2),$allNum.' 笔')->getStyle('I'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $excel->getActiveSheet()->setCellValueExplicit('J'.($k+2),$allMoney.' 元')->getStyle('J'.($k+2))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                }
            }
        }

        //清理缓冲区，避免中文乱码
        ob_end_clean();
        //导出数据
        $obj=new \PHPExcel_Writer_Excel5($excel);//实例化 将对象放入表格中
        $download_url = './uploads/1excel/'.$name.'.xlsx'; //生成表格地址
        $obj->save($download_url);
        return $download_url;
    }



}
